<?php

namespace app\adm\Controller;

use think\Db;

class Cron
{
	// 糖果机释放糖果币
	public function index()
	{
		if (! cache('sys_config')) {
            $list = \think\Db::name('config')->column('key,value');
		    cache('sys_config', $list);
        }
        config(cache('sys_config'));

		$cmList = Db::name('candy_machine')
			->where('status', 0)
			->field('cm_id,uid,candy_total,candy_now,left_days,lifetime,end')
			->select();

		$us = model('User');

		foreach ($cmList as $v) {
			$freeNum = $v['candy_total'] / $v['lifetime'];
			// 到达到账时间
			if ($v['left_days'] == 1) {
				$updateData = [
					'left_days' => 0,
					'candy_now' => $v['candy_total'],
					'status' => 1
				];
				Db::startTrans();
				try {
					$us->updateUserAcc($v['uid'], $v['candy_total'] * 0.6, 'tg_coin', '糖果机释放');
					$us->updateUserAcc($v['uid'], $v['candy_total'] * 0.3, 'hg_coin', '糖果机释放');
					//代理产生奖励
					$this->awardAgent($v['uid'], $v['candy_total']);
					Db::name('candy_machine')->where('cm_id', $v['cm_id'])->update($updateData);
					Db::commit();
				} catch (Exception $e) {
					Db::rollback();
					return $e->getMessage();
				}
			} else {
				$updateData = [
					'left_days' => $v['left_days'] - 1 ,
					'candy_now' => $v['candy_now'] + $freeNum,
				];
				Db::name('candy_machine')->where('cm_id', $v['cm_id'])->update($updateData);
			}

			$this->addCandymLog($v['cm_id'], $freeNum);
		}

		return true;
	}

	// 生成释放记录
	public function addCandymLog($cm_id, $num)
	{
		$data = [
			'cm_id' => $cm_id,
			'num' => $num,
			'create_time' => date('Y-m-d H:i:s')
		];

		db('candym_log')->insert($data);
	}

	// 产生代理奖项
	private function awardAgent($uid, $num)
	{
		$usInfo = Db::name('user')->where('uid', $uid)->field('pid,name,province,city')->find();
		$map = [
			'province' => $usInfo['province'],
			'city' => $usInfo['city'],
			'status' => 1
		];

		$agent = Db::name('agent')->where($map)->find();

		if ($agent) {
			$num = config('dl_rate') * $num / 100;
			model('User')->updateUserAcc($agent['uid'], $num, 'tg_coin', '玩家'.$usInfo['name'].'产生糖果币，代理奖励');
		}
	}

}